import { useState, useRef, useEffect } from 'react';
import { Badge } from 'antd';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { crud, buildImage, getBuildLog } from './api';
import { handleAction } from '@/utils/handler';
import BasicForm from './form';
import { getRegistryOptions } from '../Registry/api';
import BasicFormTable from '@/components/BasicFormTable';
import type { BasicDrawerRef } from '@/components/BasicDrawer';
import BasicDrawer from '@/components/BasicDrawer';
import BasicLog from '@/components/BasicLog';

export default () => {
  const tableRef = useRef<ActionType>();
  const logRef = useRef<BasicDrawerRef>(null);
  const [registryOptions, setRegistryOptions] = useState([]);
  const [currentRow, setCurrentRow] = useState<ImageEntity>();

  const onReload = () => {
    tableRef?.current?.reload();
  };

  async function initRegistryOptions() {
    const options = await getRegistryOptions();
    setRegistryOptions(options);
  }

  useEffect(() => {
    initRegistryOptions();
  }, []);

  const columns: ProColumns<ImageEntity>[] = [
    {
      title: '镜像源',
      dataIndex: 'ide_registry',
      hideInSearch: true,
      valueType: 'select',
      fieldProps: {
        options: registryOptions,
      },
    },
    {
      title: '名称',
      dataIndex: 'name',
    },
    {
      title: '版本',
      dataIndex: 'version',
      hideInSearch: true,
    },
    {
      title: 'Git地址',
      dataIndex: 'git_url',
      hideInSearch: true,
    },
    {
      title: '备注',
      dataIndex: 'note',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        return [
          <Badge key="none" status="default" text="未构建" />,
          <Badge key="running" status="processing" text="构建中" />,
          <Badge key="error" status="error" text="构建失败" />,
          <Badge key="success" status="success" text="构建成功" />,
        ][record.status];
      },
    },
    {
      title: '创建时间',
      key: 'created',
      dataIndex: 'created',
      valueType: 'dateTime',
      hideInSearch: true,
    },
  ];

  return (
    <>
      <BasicFormTable<ImageEntity>
        tableRef={tableRef}
        title={'镜像'}
        columns={columns}
        polling={(data) => (data.some((item) => item.status === 1) ? 2000 : 0)}
        crud={crud}
        addForm={<BasicForm />}
        updateForm={<BasicForm />}
        renderActions={(actions, record) => {
          const newActions = [
            <a
              key="build"
              onClick={async () => {
                const success = await handleAction<string>(record.id, buildImage, '新增构建任务');
                if (success) onReload();
              }}
            >
              构建
            </a>,
          ].concat(actions);
          if ([1, 2, 3].includes(record.status)) {
            newActions.unshift(
              <a
                key="log"
                onClick={() => {
                  setCurrentRow(record);
                  logRef.current?.open();
                }}
              >
                查看日志
              </a>,
            );
          }
          return newActions;
        }}
      />
      <BasicDrawer ref={logRef} title={`构建日志`} destroyOnClose>
        {currentRow && (
          <BasicLog<ImageEntity>
            record={currentRow}
            loadStatusAction={() => getBuildLog(currentRow.id)}
          />
        )}
      </BasicDrawer>
    </>
  );
};
